package com.soxing.webrain.brush.service.work;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.soxing.webrain.brush.dao.entity.Task;
import com.soxing.webrain.brush.dao.service.impl.TaskServiceImpl;
import com.soxing.webrain.brush.dao.service.impl.TesteeServiceImpl;
import com.soxing.webrain.brush.service.docker.MyDockerClient;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service("MyTaskExecutor")
public class MyTaskExecutor {

    @Resource
    private TesteeServiceImpl testeeService;

    @Resource
    private TaskServiceImpl taskService;

    @Resource
    MyDockerClient myDockerClient;

    private static final Logger logger = LoggerFactory.getLogger(TaskDispatch.class);

    public String execute(Task p, String image) throws Exception {

//        List<Task> pList = dispatch();
//        if (CollectionUtils.isEmpty(pList)) {
//            return;
//        }

        String containerId = myDockerClient.createJob(p, image);
        Task tmpObj = new Task();
        tmpObj.setId(p.getId());
        tmpObj.setModifyTime(new Date());

        if (containerId != null) {
            // 执行中
            tmpObj.setStatus(1);
        } else {
            // 执行失败
            tmpObj.setStatus(5);
        }
        taskService.updateById(tmpObj);

        return containerId;
    }

    public void stopTask(Task p) {
        String containerId = p.getContainerId();
        Boolean flag = myDockerClient.stopJob(containerId);
        if (flag) {
            // 等待评估
            p.setStatus(3);
        } else {
            // 执行失败
            p.setStatus(5);
        }
        taskService.updateById(p);
    }

    public void leaveTask(Task p) {
        String containerId = p.getContainerId();
        Boolean flag = myDockerClient.stopJob(containerId);
        // 终止训练
        p.setStatus(2);

        taskService.updateById(p);
    }

    public List<Task> dispatch() {
        // String maxTasksStr = parameterService.getValue(SystemParameterEnum.maxTasks.getKey());
        // if (maxTasksStr == null) {
        //     maxTasksStr = "20";
        // }
        // int maxTasks = Integer.valueOf(maxTasksStr);
        Integer maxTasks = 20;

        Map<String, Object> params = new HashMap<>();
        // 任务状态 -1:信息不完整  0:未开始  1:训练中 2:终止训练 3:等待评估 6:评估中 4:评估成功 5:执行失败
        params.put("status", 0);
        // 等待执行的任务
        List<Task> waitingProjectList = taskService.listByMap(params);
        if (CollectionUtils.isEmpty(waitingProjectList)) {
            logger.info("没有需要执行的任务");
            return null;
        }
        logger.info("待执行任务数:" + waitingProjectList.size());

        params.clear();
        params.put("status", 1);
        // 正在执行的任务数
        List<Task> runningProjectList = taskService.listByMap(params);
        // 正在执行的任务数
        int runningCount = runningProjectList == null ? 0 : runningProjectList.size();
        logger.info("当前正在执行的任务数为:" + runningCount);

        // 还能执行任务数
        int leftCount = maxTasks - runningCount;
        logger.info("系统剩余任务执行能力:" + leftCount);
        if (leftCount <= 0) {
            return null;
        }
        leftCount = Math.min(waitingProjectList.size(), leftCount);
        logger.info("本次执行任务数:" + leftCount);
        return waitingProjectList.subList(0, leftCount);
    }

}
